package com.yu.blog.cofig.security;

import com.alibaba.fastjson2.JSONObject;
import com.yu.blog.cofig.security.filter.JwtAuthenticationFilter;
import com.yu.blog.cofig.security.filter.UsernamePasswordFilter;
import com.yu.blog.cofig.security.service.AuthUserDetailsService;
import com.yu.blog.constant.ConstantData;
import com.yu.blog.enums.HttpStatusEnum;
import com.yu.blog.utils.JwtUtils;
import com.yu.blog.utils.RedisUtils.RedisUtils;
import com.yu.blog.utils.servletUtils.ResponseUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.io.IOException;
import java.util.List;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class securityConfig {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private AuthUserDetailsService authUserDetailsService;

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    private UsernamePasswordFilter usernamePasswordFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests()
                .requestMatchers(HttpMethod.GET, ConstantData.WhiteList.toArray(new String[0])).permitAll()
                .requestMatchers(HttpMethod.GET, ConstantData.MyWhiteLists.toArray(new String[0])).permitAll()
                .anyRequest().authenticated()
                .and()
                .cors().configurationSource(this.corsConfigurationSource())
                .and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .formLogin()
                .loginProcessingUrl(ConstantData.LoginUrl)
                .successHandler(this::onAuthenticationSuccess)
                .failureHandler(this::onAuthenticationFailure)
                .and()
                .logout()
                .logoutUrl(ConstantData.LogoutUrl)
                .logoutSuccessHandler(this::onLogoutSuccess)
                .and()
                .userDetailsService(authUserDetailsService)
                .exceptionHandling()
                .authenticationEntryPoint(this::commence)
                .accessDeniedHandler(this::handle)
                .and()
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(usernamePasswordFilter, JwtAuthenticationFilter.class)
                .build();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern(ConstantData.AllowedOriginPattern);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addExposedHeader(jwtUtils.getJwtTokenHeader());
        corsConfiguration.addExposedHeader(jwtUtils.getJwtRefreshTokenHeader());
        corsConfiguration.setMaxAge(3600L);
        corsConfiguration.setAllowedMethods(List.of("GET", "POST", "DELETE", "PUT"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    private void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String jwtToken = jwtUtils.generateToken(authentication.getName());
        String refreshToken = jwtUtils.createRefreshToken(authentication.getName());
        //用户角色信息存入redis
        redisUtils.set("user:" + authentication.getName() + ":role", JSONObject.toJSONString(authentication.getAuthorities()), jwtUtils.getExpirationRefreshTime() * 60 * 60 * 24);

        response.setHeader(jwtUtils.getJwtTokenHeader(), jwtToken);
        response.setHeader(jwtUtils.getJwtRefreshTokenHeader(), refreshToken);
        ResponseUtil.setSuccessResponse(response, HttpStatusEnum.LOGIN_SUCCESS);
    }

    private void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        ResponseUtil.setFailedResponse(response, HttpStatusEnum.LOGIN_AUTH_ERROR);
    }

    private void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }
        response.setHeader(jwtUtils.getJwtTokenHeader(), "");
        response.setHeader(jwtUtils.getJwtRefreshTokenHeader(), "");
        ResponseUtil.setSuccessResponse(response, HttpStatusEnum.LOGOUT_SUCCESS);
    }

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        ResponseUtil.setFailedResponse(response, HttpStatusEnum.FORBIDDEN);
    }

    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        ResponseUtil.setFailedResponse(response, HttpStatusEnum.DENIED);
    }
}
